const db = require('../db');

const purchaseListModel = {
    async getAll() {
        const [rows] = await db.execute('SELECT * FROM purchase_list WHERE status != 2');
        return rows;
    },

    async getById(id) {
        const [rows] = await db.execute('SELECT * FROM purchase_list WHERE id = ? AND status != 2', [id]);
        return rows[0];
    },

    async create(data) {
        const {
            material_list,
            subtotal,
            numbering,
            supplier,
            name,
            specification,
            quantity,
            type,
            unit,
            unit_price,
            rate,
            other_fee,
            remark,
            purchase_time,
            payment_time,
            paid,
            status
        } = data;

        const [result] = await db.execute(
            `INSERT INTO purchase_list (
        material_list, subtotal, numbering, supplier, name, specification, quantity, type, unit, 
        unit_price, rate, other_fee, remark, purchase_time, payment_time, paid, status
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
            [material_list, subtotal, numbering, supplier, name, specification, quantity, type, unit,
                unit_price, rate, other_fee, remark, purchase_time, payment_time, paid, status || 1]
        );

        return { id: result.insertId };
    },

    async update(id, data) {
        const keys = Object.keys(data);
        const values = Object.values(data);

        const setClause = keys.map(key => `${key} = ?`).join(', ');
        values.push(id);

        const [result] = await db.execute(`UPDATE purchase_list SET ${setClause} WHERE id = ?`, values);
        return result;
    },

    async delete(id) {
        const [result] = await db.execute('UPDATE purchase_list SET status = 2 WHERE id = ?', [id]);
        return result;
    }
};

module.exports = purchaseListModel;
